package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.OrderStatusEnum;
import com.atguigu.common.utils.R;
import com.atguigu.entity.to.OrderTo;
import com.atguigu.entity.to.mq.StockDetailTo;
import com.atguigu.entity.to.mq.StockLockedTo;
import com.atguigu.entity.vo.SkuHasStokeVo;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.vo.OrderItemVo;
import com.atguigu.gulimall.ware.entity.vo.OrderVo;
import com.atguigu.gulimall.ware.entity.vo.WareSkuLockVo;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    OrderFeignService orderFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        skuId=&wareId=
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStoke(Long skuId, Long wareId, Integer skuNum) {
        //判断是否存在库存，不存在新增，存在修改库存数量
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("ware_id", wareId).eq("sku_id", skuId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //需要远程查询商品系统sku名称
            //不要因为一个获取名称而影响到整个事物
            //1.可以捕获异常，不让异常抛出去，不影响事物整体
            //2。TODO
            try {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0){
                    Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                    if (skuInfo != null){
                        wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStoke(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStokeVo> hasstoke(List<Long> skuIds) {

//        select SUM(stock - stock_locked) FROM wms_ware_sku where sku_id = ?
        List<SkuHasStokeVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStokeVo vo = new SkuHasStokeVo();
            Long count = baseMapper.hasstoke(skuId);

            vo.setSkuId(skuId);
            vo.setHasStoke(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 为摸个订单锁定库存
     * @param vo
     * @return
     * //不标明异常，默认只要是运行时异常都会回滚
     * @Transactional(rollbackFor = NoStockException.class)
     *
     * 库存解锁的场景
     * 1。下单成功，订单过期没有支付，系统自动取消，或被用户手动取消，都要解锁库存
     * 2。下订单成功，库存也锁定成功，但接下来的业务失败，导致订单回滚。之前锁定的库存需要解锁
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        //保存库存工作单详情，用于追溯
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        //1。按照下单的收货地址，找到就近仓库来锁定库存
        //1。找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();

            Long skuId = item.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(item.getCount());
            //查询在哪个仓库有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareIds);

            return skuWareHasStock;
        }).collect(Collectors.toList());

        Boolean allLock = true;
        //锁定库存
        for (SkuWareHasStock skuWareHasStock : collect) {
            Boolean skuStocked = false;

            List<Long> wareIds = skuWareHasStock.getWareId();
            Long skuId = skuWareHasStock.getSkuId();
            if (wareIds == null && wareIds.size() == 0){
                //没有任何仓库有这个商品都库存
                throw new NoStockException(skuId);
            }

            //1。如果每一个商品都锁定成功，将当前商品锁定来几件都工作单记录发送给MQ
            //2。如果锁定失败，前面保存的工作信息就回滚了。已经发送出去也没问题，用id在数据库查不到消息，不用解锁（这样是不合理的）

            for (Long wareId : wareIds) {
                //成功返回大于1 失败返回0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,skuWareHasStock.getNum());
                if (count != 0){
                    skuStocked = true;

                    //TODO 告诉MQ库存锁定成功,发消息
                    //保存
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                    detailEntity.setSkuId(skuWareHasStock.getSkuId());
                    detailEntity.setSkuName("");
                    detailEntity.setSkuNum(skuWareHasStock.getNum());
                    detailEntity.setTaskId(taskEntity.getId());
                    detailEntity.setWareId(wareId);
                    detailEntity.setLockStatus(1);
                    orderTaskDetailService.save(detailEntity);

                    //锁定一个发送一条消息
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity,stockDetailTo);

                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    //只发Id不行，需要发详细的详情数据，防止回滚以后找不到数据
                    stockLockedTo.setDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo,new CorrelationData(UUID.randomUUID().toString()));
//                    rabbitTemplate

                    break;
                }
                //当前仓库锁失败，for循环换一个仓库，成功了就跳出循环
            }

            //所有仓库都没锁住
            if (skuStocked == false){
                throw new NoStockException(skuId);
            }

        }
        //3.代码到这里肯定全部都是锁定成功过的
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo lockedTo) throws IOException {
        Long id = lockedTo.getId();//库存工作单id
        StockDetailTo detailTo = lockedTo.getDetailTo();
        Long detailId = detailTo.getId();

        WareOrderTaskDetailEntity detailEntity = orderTaskDetailService.getById(detailId);
        if (detailEntity != null){
            //
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();//获取订单号
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0){
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });
                //判断订单是否存在 判断订单是否已取消，取消了才才能解锁库存
                if (orderVo == null || orderVo.getStatus() == OrderStatusEnum.CANCLED.getCode()){
                    //当前工作单属于已锁定 但未解锁才可以解锁
                    if (detailEntity.getLockStatus() == 1){
                        unLockStock(detailTo.getSkuId(),detailTo.getWareId(),detailTo.getSkuNum(),detailId);
                    }
//                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }

//                Integer status = orderVo.getStatus();
//                //判断订单是否已取消，取消了才才能解锁库存
//                if (status == OrderStatusEnum.CANCLED.getCode()){
//                    unLockStock(detailTo.getSkuId(),detailTo.getWareId(),detailTo.getSkuNum(),detailId);
////                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//                }
            }else {
                //远程接口调失败了，拒绝消息后，把消息放回队列，让别人继续解锁
//                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
                throw new RuntimeException("远程服务调用失败");
            }
//            if ()
        }else {
            //无需解锁,也要告诉服务器，删除消息
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

    /**
     * 防止订单卡顿，导致订单状态一直改不了，库存消息优先到期，导致库存无法解锁
     * 订单解锁后主动发消息来解锁
     * @param to
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {

        String orderSn = to.getOrderSn();
        //发过来的消息是最新的，这里可查可不查最新的订单信息

        //查询一下库存解锁的状态，防止重复解锁
        WareOrderTaskEntity taskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = taskEntity.getId();
        //按照工作单找到所有状态没有解锁的
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));

        if (list == null || list.size() == 0){
            return;
        }

        for (WareOrderTaskDetailEntity detailEntity : list) {
            unLockStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum(),detailEntity.getId());
        }

    }

    /**
     * 解锁库存
     * @param skuId
     * @param wareId
     * @param num
     * @param taskId
     */
    private void unLockStock(Long skuId,Long wareId,Integer num, Long taskId){
        //库存解锁
        wareSkuDao.unLockStock(skuId, wareId, num,  taskId);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskId);
        detailEntity.setLockStatus(2);//已解锁
        orderTaskDetailService.updateById(detailEntity);

    }

    @Data
    class  SkuWareHasStock{
        private Long skuId;
        private Integer num;//锁几件
        private List<Long> wareId;//仓库id
    }
}